# -*- coding: utf-8 -*-
# @Time    : 2022/6/28 16:34
# @Author  : AUGUS
# @Email   : augus@jilin.com
# @File    : permission.py
# @Software: PyCharm
from functools import update_wrapper

from django.contrib.auth.models import Group
from rest_framework.permissions import BasePermission


class TeacherPermission(BasePermission):
    def has_permission(self, request, view):
        user = request.user  # 当前请求得用户信息
        # 判断身份，查询用户在不在老师这个分组里面
        group = Group.objects.filter(name='老师').first()
        # print(group)
        user_groups = user.groups.all()
        return user.is_superuser or group in user_groups


class ActiveUserPermission(BasePermission):
    def has_permission(self, request, view):
        user = request.user
        return user.id == int(view.kwargs['pk'])  # 当前登录用户与路由上的传入进来的id是否相同


# 更改权限装饰器
def wrap_permisssion(*permissions, validate_permission=True):
    def decorator(func):
        def wrapper(self, request, *args, **kwargs):
            self.permission_classes = permissions
            if validate_permission:
                self.check_permissions(request)
            return func(self, request, *args, **kwargs)

        return update_wrapper(wrapper, func)

    return decorator
